package com.example.petstore.ws;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.alibaba.fastjson.JSON;
//import com.example.petstore.config.HttpSessionConfig;
import com.example.petstore.common.CommonResponse;
import com.example.petstore.domain.Admin;
import com.example.petstore.domain.Message;
import com.example.petstore.domain.User;
import com.example.petstore.service.AdminService;
import com.example.petstore.service.MessageService;
import com.example.petstore.service.UserService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;


@ServerEndpoint(value = "/chat/{customerID}")
@Component
public class WebSocketHandle {

    //    @Autowired
    private static AdminService adminService;
    @Autowired
    private void setAdminService(AdminService adminService){
        WebSocketHandle.adminService = adminService;
    }
    private static UserService userService;
    @Autowired
    private void setUserService(UserService userService){
        WebSocketHandle.userService = userService;
    }
    //    @Autowired
    private static MessageService messageService;
    @Autowired
    private void setMessageService(MessageService messageService){
        WebSocketHandle.messageService = messageService;
    }



    private static Map<String, Set<Session>> userChannels = new HashMap<>();
    @OnOpen
    public void onOpen(Session session) {
        // 从 WebSocket 连接中获取 customerID
        String customerID = session.getRequestURI().getPath().split("/")[2];
        System.out.println("c"+customerID);
        session.getUserProperties().put("customerID", customerID);
        if (!userChannels.containsKey(customerID)) {
            userChannels.put(customerID, new HashSet<>());
        }

        userChannels.get(customerID).add(session);
//        messageService = new MessageService();
        List<Message> messageList = messageService.selectMessagesByUserIdOrderByTime(customerID);
        System.out.println(messageList);
        String jsonString = JSON.toJSONString(messageList);
        System.out.println(jsonString);
        sendMessageToUser(customerID, jsonString);//把聊天记录发送给前端
    }


    //var socket = new WebSocket("ws://example.com/chat");
    //socket.userType = "admin";前端设置
    @OnClose
    public void onClose(Session session) {
        System.out.println("ddd");
        String customerID = session.getRequestURI().getPath().split("/")[2];

        if (userChannels.containsKey(customerID)) {
            System.out.println("ad");
            userChannels.get(customerID).remove(session);
//            String userType = (String) session.getUserProperties().get("userType");
//            HttpSession httpSession = (HttpSession) session.getUserProperties().get(HttpSession.class.getName());
//            System.out.println(userType);

        }
    }



    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("eeeee");
        String customerID = session.getRequestURI().getPath().split("/")[2];
        if (customerID != null) {
            try {
                // 解析收到的JSON消息
                ObjectMapper objectMapper = new ObjectMapper();
                System.out.println(message);
                try {
                    // 解析 JSON 字符串
                    JsonNode jsonNode = objectMapper.readTree(message);
                    String adminname = jsonNode.get("adminname").asText();
                    String content = jsonNode.get("content").asText();
                    String createTime = jsonNode.get("createTime").asText();
                    System.out.println(createTime);
                    String username = jsonNode.get("username").asText();
                    String direction = jsonNode.get("direction").asText();
                    // 定义日期时间格式
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");

                    // 将字符串解析为 LocalDateTime 对象
                    LocalDateTime localDateTime = LocalDateTime.parse(createTime, formatter);
                    Message msg = new Message();
                    msg.setAdminname(adminname);
                    msg.setContent(content);
                    msg.setUsername(username);
                    msg.setDirection(Integer.parseInt(direction));
                    msg.setCreateTime(localDateTime);
                    System.out.println("l:"+localDateTime);
//                    System.out.println();
                    System.out.println(msg);
                    CommonResponse commonResponse = messageService.insertChat(msg);
                    System.out.println(commonResponse.getData());



                } catch (Exception e) {
                    e.printStackTrace();

                }
                // 将 JSON 字符串转换为 Message 对象
                //  Message msg = objectMapper.readValue(message, Message.class);
                // messageService.insertChat(msg);

                List<Message> messageList = messageService.selectMessagesByUserIdOrderByTime(customerID);
                String jsonString = JSON.toJSONString(messageList);
                sendMessageToUser(customerID, jsonString);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @OnError
    public void onError(Throwable error) {
        error.printStackTrace();
    }



    private void sendMessageToUser(String customerID, String message) {
        if (userChannels.containsKey(customerID)) {
            for (Session session : userChannels.get(customerID)) {
                try {
                    session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



}

